<!-- 
	* 摘要：企业管理
	* 软件名称：雪克码数据管理系统1.0
	* 文件名: enterprises.vue
	* 版本：1.0
 -->
<template>
	<div class="sn-common-container ">
		<div class="prcoss-container">
			<header>
				<div class="sn-flex sn-row-center hidden-sm-and-down">
					<el-select v-model="isDelete" value-key="" placeholder="是否删除" @change="currentChange(1)" style="width: 120px;margin-right: 10px;" clearable filterable >
						<el-option :label="'全部'" :value="'all'"></el-option>
						<el-option :label="'已删除'" :value="true"></el-option>
						<el-option :label="'未删除'" :value="false"></el-option>
					</el-select>
					<el-select
						@change="currentChange(1)"
						v-model="fillterSaleman"
						collapse-tags
						filterable
						placeholder="选择业务员筛选"
						clearable
						style="width: 200px; margin: 0 10px 0 0px"
					>
					<el-option  :label="'未配置'" style="border-bottom:1px solid #eaeaea" :value="'00000000-0000-0000-0000-000000000000'" />
						<el-option v-for="item in salemanList" :key="item.userId" :label="item.employeeName" :value="item.userId" />
					</el-select>
					<el-input v-model="searchValue" placeholder="输入企业名称筛选" style="width: 200px" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
						@click="currentChange(1)">
						搜索
					</el-button>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
						@click="addUserDialog = true">
						新建企业
					</el-button>
				</div>
				<div class="hidden-sm-and-up">
					<el-input v-model="searchValue" placeholder="输入企业名称筛选" style="width: 200px" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
						@click="currentChange(1)">
					</el-button>
					<el-button style="margin-left: 4px" type="primary" class="sn-btn" @click="addUserDialog = true">
						新增
					</el-button>
				</div>
			</header>
			<section>
				<global-table :loading="tableLoading" style="margin-top: 20px;" :pageIndex="currentPage"
					:pageSize="pageSize" :headerData="initData" :data="tabelData" :isFullScreen="false" :operateW="500">
					<template #managerName="scope">
						<span style="margin-right: 10px;">{{ scope.row.managerId?(scope.row.managerName || '未实名'):'未配置' }}</span>
						<span class="el-icon-edit sn-hover"  @click="openConfigPersonFn(scope.row,1)"></span>
					</template>
					<template #isAuth="scope">
						<span>{{scope.row.authentication?'已认证':'未认证' }}</span>，
						<span class="sn-hover" style="color: #ccc;;" v-if="scope.row.authentication" @click="cancelShopAuthFn(scope.row.id)">取消认证</span>
						<span class="sn-hover" style="color:#409EFF" v-else @click="shopAuthFn(scope.row.id)">手动认证</span>
					</template>
					
					<template #operate="scope">
						<span v-if="!scope.row.isDeleted">
							<el-button type="primary" size="mini" @click="lookShopOpen(scope.row)">查看</el-button>
							<el-button type="primary" size="mini" @click="lookWarehouseOpen(scope.row.id)">配置</el-button>
							<el-button type="primary" size="mini" @click="openDialogFn(scope.row.id,1)">职位</el-button>
							<el-button type="primary" size="mini" @click="openDialogFn(scope.row.id,2)">员工</el-button>
							<el-button type="primary" size="mini" @click="openDialogFn(scope.row.id,3)">功能</el-button>
							<el-button type="primary" size="mini" @click="switchShopStatusFn(scope.row)">{{!scope.row.status ? '营业' : '停业' }}</el-button>
							<el-button type="primary" class="sn-btn" icon="el-icon-delete" size="mini" @click="delShopFn(scope.row.id,false)">删除</el-button>
						</span>
						<span v-else>
							<el-button type="primary" size="mini" @click="resetDeleteFn(scope.row.id)">恢复正常</el-button>
							<el-button type="primary" size="mini" class="sn-btn" @click="delShopFn(scope.row.id,true)">彻底删除</el-button>
						</span>
					</template>
				</global-table>
			</section>
			<footer style="margin-top: 20px;">
				<el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
					layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-page
					style="text-align: center;" :total="totalNum" background>
					>
				</el-pagination>
			</footer>
		</div>
		<!-- 新增企业弹窗 -->
		<el-dialog :visible.sync="addUserDialog" class="sn-default-dialog" width="360px" @close="addUserDialogClose()">
			<div class="sn-title" slot="title">{{authShopFlag?'企业认证':'新增企业'}}</div>
			<div v-loading="addShopLoading">
				<global-upload  :isIdcard="true" :isCreateShop="true" :key="'front+dasda'"
					:isIdcardFront="true" @imageUpload="businessLicenseUploadFn" @imageRemove="businessLicenseRemoveFn"
					:initOne="chooseShopInfo.businessLicenseResourceId" :isHeadImg="true">
				</global-upload>
				<p>企业名称：</p>
				<el-input v-model="chooseShopInfo.name" placeholder="请输入企业名称" style=""></el-input>
				<p>营业执照编码：</p>
				<el-input v-model="chooseShopInfo.unifiedSocialCreditCode" placeholder="请输入营业执照编码" style=""></el-input>
				<p>企业法人名称：</p>
				<el-input v-model="chooseShopInfo.legalPersonName" placeholder="请输入企业法人名称" style=""></el-input>
				<div v-if="!authShopFlag">
					<p>企业经营地址：</p>
					<address-select v-if="addUserDialog" :centerMargin="6" :rightMargin="0" @address-id="getSalesAddressIdFn" :boxWidth="'100px'" :chooseProvinceId="chooseShopInfo.provinceId" :chooseCityId="chooseShopInfo.cityId" :chooseAreaId="chooseShopInfo.regionId"></address-select>          
					<p>企业仓库类型：</p>
					<el-select v-model="chooseShopInfo.inventorySystemType" value-key="" placeholder="选择仓库类型"   >
						<el-option :label="'畅捷通'" :value="1"></el-option>
						<el-option :label="'管家婆'" :value="2"></el-option>
					</el-select>
				</div>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="addShopFn()">保存</el-button>
					<el-button size="medium" @click="addUserDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<!-- 查看企业信息 -->
		<el-dialog :visible.sync="lookShopDialog" class="sn-default-dialog" width="360px">
			<div class="sn-title" slot="title">查看企业详情</div>
			<div>
				<p style="margin-top: 0;">企业名称：{{ chooseShopInfo.name || '未设置' }}</p>
				<p style="margin-top: 0;">营业执照名称：{{ chooseShopInfo.licenseName || '未设置' }}</p>
				<p style="margin-top: 0;">营业执照编码：{{ chooseShopInfo.unifiedSocialCreditCode || '未设置' }}</p>
				<p style="margin-top: 0;">法人姓名：{{ chooseShopInfo.legalPersonName || '未设置' }}</p>
				<p style="margin-top: 0;">经营区域：{{ chooseShopInfo.provinceName+chooseShopInfo.cityName+chooseShopInfo.regionName}}</p>
				<p style="margin-top: 0;">关联积分调酒师昵称：{{ chooseShopInfo.bartenderNickname || '未设置' }}</p>
				<p style="margin-top: 0;">关联积分调酒师真实姓名：{{ chooseShopInfo.bartenderRealName || '未设置' }}</p>
				<p style="margin-top: 0;">关联业务员名称：{{ chooseShopInfo.salesmanName || '未设置' }}</p>
			</div>
		</el-dialog>
		<!-- 配置业务负责人/积分调酒师/星宿调酒师 -->
		<el-dialog
		:visible.sync="configPersonDialog"
		class="sn-default-dialog"
		width="360px"
		@close="configPersonClose"
		>
			<div class="sn-title" slot="title">{{ configTitle }}</div>
			<div v-loading="configLoading">
				<choose-person @choosePerson="personChange" v-if="configPersonDialog" :enterpriseId="configShopId" :personId="configPersonId" :type="configType"></choose-person>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="saveConfigPersonFn()">确定</el-button>
					<el-button size="medium" @click="configPersonDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<!-- 菜单弹窗 -->
		<el-dialog
		:visible.sync="configDialog"
		@close="configClose"
		class="sn-default-dialog"
		:close-on-click-modal="false"
		width="660px"
		>
			<div class="sn-title" slot="title">{{ configTitle}}</div>
			<div  v-if="configMenuDialog&&configDialog" >
				<config-menu :enterpriseId="configShopId" ></config-menu>
			</div>
			<div  v-if="positionDialog&&configDialog" >
				<position-mange :enterpriseId="configShopId" ></position-mange>
			</div>
			<div  v-if="staffDialog&&configDialog" >
				<staff-mange  :enterpriseId="configShopId" ></staff-mange>
			</div>
		</el-dialog>
		<!-- 仓库配置 -->
		 <el-dialog
		 :visible.sync="warehouseDialog"
		 class="sn-default-dialog"
		 width="500px"
		 >
		 <div class="sn-title" slot="title">仓库配置</div>
		 <div>
			<div v-loading="shopConfigLoading" style="min-height: 200px;border:1px solid #f2f2f2;padding:10px;max-height: 400px;overflow-y: auto;">
				<div v-if="shopConfigList.length>0" >
					<p v-for="item in shopConfigList" :key="item.id" style="margin-top: 0;">
						<span>{{item.name}}:</span>
						<span>{{item.value}}</span>
						<span class="sn-hover el-icon-edit" style="margin-left:20px;" @click="openNewConfig('edit',item)">编辑</span>
					</p>
				</div>
				<div v-else style="text-align: center;">
					该企业没有进行任何配置
				</div>
			</div>
			<p style="text-align: center;">
				<el-button type="primary" size="medium" class="sn-btn" @click="openNewConfig('add')">新增配置</el-button>
				<el-button size="medium" @click="warehouseDialog = false">取消</el-button>
			</p>
		 </div>
		 </el-dialog>
		 <!-- 新建配置 -->
		  <el-dialog
		  :visible.sync="newConfigDialog"
		  append-to-body
		  width="360px"
		  class="sn-default-dialog"
		  >
		  <div class="sn-title" slot="title">{{ newConfigType ==='add'?'新增配置':'编辑配置' }}</div>
		  <div>
			<p>配置名称：</p>
			<el-input v-model="chooseConfig.name" placeholder="请输入配置名称" style=""></el-input>
			<p>配置key（仓库配置代码--- warehouseCode）：</p>
			<el-input v-model="chooseConfig.key" placeholder="请输入配置key" style=""></el-input>
			<p>配置value（多个value的话用“,”隔开）：</p>
			<el-input v-model="chooseConfig.value" placeholder="请输入配置value" style=""></el-input>
		  </div>
		  <p style="text-align: center;">
				<el-button type="primary" size="medium" class="sn-btn" @click="editConfigFn()">新增配置</el-button>
				<el-button size="medium" @click="newConfigDialog = false">取消</el-button>
			</p>
		  </el-dialog>
	</div>
</template>
  
<script>
import { 
	 GetEnterprisesByPage, GetEnterprise, DeleteEnterprise, 
	  MannualAddEnterprise, SetEnterpriseStatus, 
	  SetPointBartender,RemoveSalesman,SetManager,
	  ManualEnterpriseAuthentication,GetEnterpriseConfigure,
	  AddConfigure,UpdateConfigure,
 } from '@/api/enterprise';
import { guid } from '@/utils';
import {GetEmployeePage} from '@/api/accessmanage';
import { RestoreDeleteData } from '@/api/user';
import GlobalTable from '@/components/GlobalTable';
import GlobalUpload from '@/components/GlobalUpload';
import AddressSelect from '@/components/AddressSelect';
import ChoosePerson from './ChoosePerson.vue';
import ConfigMenu from './ConfigMenu.vue'
import PositionMange from './PositionMange.vue';
import StaffMange from './StaffMange.vue';
export default {
	components: { GlobalTable,  GlobalUpload,AddressSelect,ChoosePerson,ConfigMenu,PositionMange,StaffMange },
	data() {
		return {
			warehouseDialog:false,
			tableLoading: false,
			tabelData: [],
			initData: [//表单的显示配置
				{
					label: '企业名称',
					value: 'name',
					id: guid(),
					width: 200
				},
				{
					label: '营业执照',
					value: 'businessLicenseUrl',
					id: guid(),
					type: 'img',
					imgStyle: {
						width: '120px',
						height: '50px'
					}
				},
				{
					label: '法人名称',
					value: 'legalPersonName',
					id: guid(),
					width: 100
				},
				{
					label: '是否认证',
					value: 'isAuth',
					id: guid(),
					isCustom: true,
					width: 200
				},
				{
					label: '管理员',
					value: 'managerName',
					id: guid(),
					isCustom: true,
				},
			],
			currentPage: 1,
			pageSize: 10,
			totalNum: 0,
			searchValue: '',
			addUserDialog: false,
			addShopLoading: false,
			lookShopDialog: false,
			chooseShopInfo:{},
			configPersonDialog:false,
			configTitle:'',
			configType:0,
			configPersonId:'',
			configShopId:'',
			configLoading:false,
			isDelete:false,
			authShopFlag:false,
			salemanList:[],
			fillterSaleman:'',
			configDialog:false,
			configMenuDialog:false,
			positionDialog:false,
			staffDialog:false,
			shopConfigList:[],
			shopConfigLoading:false,
			newConfigDialog:false,
			newConfigType:0,
			chooseConfig:{},
		}
	},
	created() {
		this.getSalemanListFn();
		this.getDataListFn();
	},
	methods: {
		async editConfigFn(){
			let res;
			this.chooseConfig.enterpriseId = this.configShopId;
			if(this.newConfigType === 'add'){
				res = await AddConfigure(this.chooseConfig);
			}else{
				res = await UpdateConfigure(this.chooseConfig);
			}
			if(res.code === 200){
				this.newConfigDialog = false;
				this.lookWarehouseOpen(this.configShopId);
			}else{
				this.$message.error('保存失败，错误信息：'+res.erroMessage)
			}
		},
		openNewConfig(type,config){
			this.newConfigType = type;
			if(type === 'add'){
				this.chooseConfig = {};
			}else{
				this.chooseConfig = config;
			}
			this.newConfigDialog = true;
		},
		async lookWarehouseOpen(shopId){
			this.warehouseDialog = true;
			this.configShopId = shopId;
			this.shopConfigLoading = true;
			const res = await GetEnterpriseConfigure({enterpriseId:shopId});
			this.shopConfigLoading = false;
			if(res.code === 200){
				this.shopConfigList = res.data;
			}else{
				this.$message.error('获取企业配置失败，错误信息：'+res.erroMessage)
			}
		},
		configClose(){
			this.positionDialog = false;
			this.configMenuDialog = false;
			this.staffDialog = false;
			this.configDialog = false;
		},
		// 获取筛选的业务员列表
		async getSalemanListFn(){
			let params = {
				pageIndex: 1,
				pageSize: 999
			}
			let res = await GetEmployeePage(params);
			if(res.code === 200){
				this.salemanList = res.data.list;
			}else{
				this.$message.error('获取业务员列表失败，错误信息：'+res.erroMessage)
			}
		},
		shopAuthFn(id){
			this.configShopId = id;
			this.authShopFlag = true;
			this.addUserDialog = true;
		},
		openDialogFn(id,type){
			switch (type) {
				case 1:
					this.positionDialog = true;
					this.configTitle = '配置职位';
					break;
				case 2:
					this.staffDialog = true;
					this.configTitle = '配置员工';
					break;
				case 3:
					this.configMenuDialog = true;
					this.configTitle = '配置功能权限';
					break;
				default:
					break;
			};
			this.configShopId = id;
			this.configDialog = true;
		},
		lookPositionOpen(id){
			this.configShopId = id;
			this.positionDialog = true;
		},
		// 取消企业实名
		async cancelShopAuthFn(id){
			this.$confirm('您确定要取消该企业的实名认证吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.tableLoading = true;
				try {
					let res = await ManualEnterpriseAuthentication({ enterpriseId: id,authentication:false  });
					this.tableLoading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '取消成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('取消失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.tableLoading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消修改'
				});
			});
		},
		// 恢复删除
		resetDeleteFn(id){
			this.$confirm('您确定要将该企业恢复？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await RestoreDeleteData({ id: id,type:'Enterprise' });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '恢复成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('恢复失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		delPersonFn(id){
			this.$confirm('您将要移除业务负责人, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await RemoveSalesman({ id: id });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('删除失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 配置人员弹窗关闭
		configPersonClose(){
			this.configLoading = false;
			this.configShopId = '';
			this.configPersonId = '';
			this.configTitle = '';
			this.configType = 0;
		},
		// 配置企业的业务负责人和积分调酒师
		async saveConfigPersonFn(){
			this.configLoading = true;
			let res;
			let params = {
				id:this.configShopId
			}
			if(this.configType === 1){
				params.enterpriseId = this.configShopId;
				params.managerId = this.configPersonId;
				delete params.id;
				res = await SetManager(params);
			}
			if(this.configType === 2){
				params.bartenderId = this.configPersonId;
				res = await SetPointBartender(params);
			}
			this.configLoading = false;
			if(res.code == 200){
				this.$message.success('配置成功');
				this.configPersonDialog = false;
				this.getDataListFn();
			}else{
				this.$message.error('配置失败，错误信息：'+res.erroMessage);
			}
		},
		// 选取人员发生变化
		personChange(person){
			console.log(person);
			this.configPersonId = person;
		},
		// 营业执照扫描件上传成功
		businessLicenseUploadFn(val)  {
			this.chooseShopInfo.businessLicenseResourceId = val.local;
		},
		// 营业执照扫描件删除成功
		businessLicenseRemoveFn() {
			this.chooseShopInfo.businessLicenseResourceId = '';
		},
		// 默认给地址框赋值
		getSalesAddressIdFn(data){
			this.chooseShopInfo.regionId = data.regionId;
		},
		// 删除企业
		delShopFn(id,isDelted) {
			let msg = isDelted?'彻底删除':'删除';
			this.$confirm('您将要'+msg+'该企业, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await DeleteEnterprise({ id: id,Thoroughly:isDelted  });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('删除失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 打开配置人员弹窗
		async openConfigPersonFn(data,type) {
			this.configType= type;
			this.configShopId = data.id;
			if(type === 1){
				this.configTitle='配置业务负责人';
				this.configPersonId = data.salesmanId;
			}
			this.configPersonDialog = true;
		},
		// 打开查看企业信息弹窗
		async lookShopOpen(data) {
			const res = await GetEnterprise({id:data.id});
			if(res.code === 200){
				this.chooseShopInfo = res.data;
				this.lookShopDialog = true;
			}else{
				this.$message.error('获取企业信息失败，错误信息：' + res.erroMessage);
			}
		},
		//解锁或锁定企业
		async switchShopStatusFn(shop) {
			this.tableLoading = true;
			try {
				let res = await SetEnterpriseStatus({ id: shop.id,status:shop.status?0:1 });
				this.tableLoading = false;
				if (res.code === 200) {
					this.$message.success('切换企业经营状态成功！');
					this.getDataListFn()
				} else {
					this.$message.error('切换企业经营状态失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.tableLoading = false;
				this.$message.error("请求服务器错误，错误信息：" + error);
			}
		},
		//新建企业
		async addShopFn() {
			this.addShopLoading = true;
			let res,msg;
			if(this.authShopFlag){
				this.chooseShopInfo.licenseName = this.chooseShopInfo.name;
				this.chooseShopInfo.enterpriseId = this.configShopId;
				this.chooseShopInfo.authentication = true;
				res = await ManualEnterpriseAuthentication(this.chooseShopInfo);
				msg = '认证';
			}else{
				if(!this.chooseShopInfo.inventorySystemType){
					this.$message.error('请选择库存系统类型');
					return false;
				}
				delete this.chooseShopInfo.authentication;
				delete this.chooseShopInfo.licenseName;
				delete this.chooseShopInfo.enterpriseId;
				res = await MannualAddEnterprise(this.chooseShopInfo);
				msg = '新增';
			}
			this.addShopLoading = false;
			if (res.code === 200) {
				this.$message.success(msg+'企业成功');
				this.addUserDialog = false;
				this.getDataListFn();
			} else {
				this.$message.error(msg+'企业失败，错误信息：' + res.erroMessage)
			}
		},
		// 关闭新增企业信息窗口
		addUserDialogClose() {
			this.chooseShopInfo = {};
			this.addShopLoading = false;
			this.authShopFlag = false;
		},
		//   分页器变化
		currentChange(val) {
			this.currentPage = val;
			this.getDataListFn();
		},
		//获取企业列表
		async getDataListFn() {
			this.tableLoading = true;
			let params = {
				pageIndex: this.currentPage,
				pageSize: this.pageSize,
				Name: this.searchValue,
			}
			if(this.isDelete !=='all'){
				params.IsDeleted = this.isDelete;
			}
			if(this.fillterSaleman !==''){
				params.SalesmanId = this.fillterSaleman;
			}
			try {
				const res = await GetEnterprisesByPage(params);
				this.tableLoading = false;
				if (res.code === 200) {
					this.tabelData = res.data.list;
					this.totalNum = res.data.totalCount;
				} else {
					this.tabelData = [];
					this.$message.error('获取员工列表失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.tableLoading = false;
			}
		},
	}
};
</script>
  
<style lang="scss" scoped>
.prcoss-container {
	box-sizing: border-box;
	padding: 20px;
	background-color: #fff;
}
</style>